package com.gimi.cloud.jimi.commonService.common.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.jimi.common.utils.CommonUtil;
import com.gimi.cloud.jimi.common.utils.DateUtil;
import com.gimi.cloud.jimi.common.utils.JsonUtil;
import com.gimi.cloud.jimi.common.utils.oss.AliOSSUtil;
import com.gimi.cloud.jimi.commonService.InterfacePlatform.InterfacePlatformRequestService;
import com.gimi.cloud.jimi.commonService.common.CommonJxlService;
import com.gimi.cloud.jimi.dao.dao.userInfo.RdJxlLogDao;
import com.gimi.cloud.jimi.dao.dao.userInfo.RdMiguanLogDao;
import com.gimi.cloud.jimi.dto.userInfo.RdJxlDTO;
import com.gimi.cloud.jimi.dto.userInfo.RdMiguanDTO;
import com.gimi.cloud.jimi.dto.userInfo.RdUserInfoDTO;
import com.gimi.cloud.jimi.entity.userInfo.RdJxlLog;
import com.gimi.cloud.jimi.entity.userInfo.RdMiguan;
import com.gimi.cloud.jimi.dto.params.InterfaceCenterParams;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommonJxlServiceImpl implements CommonJxlService {

    private static Logger logger = LoggerFactory.getLogger(CommonJxlServiceImpl.class);
    @Autowired
    private InterfacePlatformRequestService interfacePlatformRequestService;
    @Autowired
    private RdJxlLogDao rdJxlLogDao;
    @Autowired
    private RdMiguanLogDao rdMiguanLogDao;

    // 蜜罐授权成功的CODE码
    private final static String SUCCESSCODE = "MIGUAN_ACCESS_SUCCESS";
    // 获取蜜罐查询成功CODE码
    private final static String SUCCESSCODEFORSEARCH = "MIGUAN_SEARCH_SUCCESS";
    // OSS上蜜罐的路径
    private final static String DIRPATH = "miguaninfo";
    // OSS上蜜罐目录
    private final static String MIGUANOSS = "miguanOSS";
    // 上传OSS成功FLAG
    private final static int SUCCESSFLAG = 1;
    // 上传OSS失败FLAG
    private final static int SUCCESSFAIL = 2;
    // 0代表授权接口类型
    private final static String MIGUANTOKEN = "0";
    // 1代表信息接口类型
    private final static String MIGUANINFO = "1";

    @Override
    public String getJxlByToken(String token) {

        return null;
    }

    @Override
    public RdJxlDTO saveUserJxlRaw(RdJxlDTO jxl) {
        String token = jxl.getToken();
        InterfaceCenterParams param = new InterfaceCenterParams("juxinli_data_by_token","juxinliinterface");
        param.addParam("token", token);
        try {
            RdJxlLog log = new RdJxlLog();
            log.setRequestUrl("juxinli_data_by_token");
            log.setRequestParam(JsonUtil.toJson(param));
            log.setRequestTime(new Date());
            log.setDescription("根据token返回JSON分析数据");
            String result = interfacePlatformRequestService.sendApiPost(JsonUtil.toJson(param));
            log.setResponse(result);
            log.setResponseTime(new Date());
            log.setJxlId(jxl.getjId());
            log.setUserId(jxl.getUserId());
            log.setToken(token);
            rdJxlLogDao.baseInsert(log);
            JSONObject json = JSON.parseObject(result);
            JSONObject jsonHead = json.getJSONObject("head");
            JSONObject jsonBody = json.getJSONObject("body");
            if("true".equals(jsonBody.getString("success"))) {
                //设置结果为获取成功
                jxl.setGetdata("2");
                jxl.setReportData(jsonBody.toJSONString());
            } else {
                jxl.setGetdataErrorTimes(jxl.getGetdataErrorTimes() == null ? 0 : jxl.getGetdataErrorTimes() + 1);
                //获取错误次数等于最大获取错误次数则标记为获取失败
                if (jxl.getGetdataErrorTimes() >= jxl.getGetdataMaxTimes()) {
                    jxl.setGetdata("3");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            jxl.setGetdataErrorTimes(jxl.getGetdataErrorTimes() == null ? 0 : jxl.getGetdataErrorTimes() + 1);
            //获取错误次数等于最大获取错误次数则标记为获取失败
            if (jxl.getGetdataErrorTimes() >= jxl.getGetdataMaxTimes()) {
                jxl.setGetdata("3");
            }
        }

        return jxl;
    }

    @Override
    public String saveUserJxl(RdUserInfoDTO userInfo) {
        InterfaceCenterParams param = new InterfaceCenterParams("juxinli_data_by_user", "juxinliinterface");
        param.addParam("name", userInfo.getRealName());
        param.addParam("idcard", userInfo.getCardId());
        param.addParam("phone", userInfo.getMobilePhone());
        try {
            String result = interfacePlatformRequestService.sendApiPost(JsonUtil.toJson(param));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void toGetTokenAndInfo(RdUserInfoDTO user) throws IOException {
        logger.info("=====================蜜罐授权接口开始，user_id=" + user.getUserId() + "========================");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RdMiguan miguanLogToken = new RdMiguan();
        miguanLogToken.setUserId(user.getUserId());
        //TripartiteAccount miguanToken = Global.getTripartiteAccount("miguan_token");
        // 拼接参数
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        //TODO 放入数据库
        String miguanAccount = "";
        String miguanClientSecret = "";
        String miguanUrl = "";
        parameters.add(new BasicNameValuePair("account", miguanAccount));
        parameters.add(new BasicNameValuePair("client_secret", miguanClientSecret));
        String param = URLEncodedUtils.format(parameters, "UTF-8");

        logger.info("授权调用.............................." + param);
        miguanLogToken.setRequestParam(param);
        miguanLogToken.setRequestDate(DateUtil.getNow());
        miguanLogToken.setRequestUrl(miguanUrl);
        // 调用授权接口

        HttpGet httpGet = new HttpGet(miguanUrl + "?" + param);
        String ret = EntityUtils.toString(httpClient.execute(httpGet).getEntity());
        logger.info("===============调用蜜罐授权后返回结果ret为" + ret + "===============");
        //返回JSON过大，暂时不存放在数据库，存入OSS
//		miguanLogToken.setResponse(ret);
        miguanLogToken.setResponseDate(DateUtil.getNow());
        miguanLogToken.setDes(MIGUANTOKEN);
        // 存入蜜罐授权日志
        rdMiguanLogDao.baseInsert(miguanLogToken);
        logger.info("=====================蜜罐授权接口结束=========================");

        logger.info("=====================获取蜜罐接口信息开始，user_id=" + user.getUserId() + "=========================");
        JSONObject tokenJson = JSON.parseObject(ret);
        if (null != tokenJson.get("code").toString() && SUCCESSCODE.equals(tokenJson.get("code").toString())) {
            //TripartiteAccount miguanReport = Global.getTripartiteAccount("miguan_report");

            String miguanReportUrl = "";
            RdMiguan miguanLog = new RdMiguan();
            miguanLog.setUserId(user.getUserId());
            miguanLog.setRequestUrl(miguanReportUrl);
            miguanLog.setRequestDate(DateUtil.getNow());
            JSONObject dataJson = (JSONObject) JSON.parse(tokenJson.get("data").toString());
            String token = dataJson.get("access_token").toString();
            parameters.add(new BasicNameValuePair("name", user.getRealName()));
            parameters.add(new BasicNameValuePair("id_card", user.getCardId()));
            parameters.add(new BasicNameValuePair("phone", user.getMobilePhone()));
            parameters.add(new BasicNameValuePair("access_token", token));
            param = URLEncodedUtils.format(parameters, "UTF-8");
            logger.info("调用蜜罐信息接口.............................." + param);
            miguanLog.setRequestParam(param);
            // 调用蜜罐信息接口
            HttpGet httpGet1 = new HttpGet(miguanReportUrl + "?" + param);
            String ret1 = EntityUtils.toString(httpClient.execute(httpGet1).getEntity());
//			String ret1="{\"code\":\"MIGUAN_SEARCH_SUCCESS1\",\"message\":\"获取蜜罐查询成功\",\"data\":{},\"spend_time\": 283}";
            logger.info("===============调用蜜罐信息后返回结果ret1为" + ret1 + "===============");
            JSONObject resultJson = JSON.parseObject(ret1);
            if (resultJson == null || !SUCCESSCODEFORSEARCH.equals(resultJson.get("code").toString())) {
                logger.info("=====================获取蜜罐接口信息结束，返回结果resultJson为" + resultJson + "或者获取蜜罐查询成功CODE码不为"
                        + SUCCESSCODEFORSEARCH + "=====================");
                return;
            }
            miguanLog.setResponseDate(DateUtil.getNow());
            //返回JSON过大，暂时不存放在数据库，存入OSS
//			miguanLog.setResponse(ret1);
            miguanLog.setDes(MIGUANINFO);
            rdMiguanLogDao.baseInsert(miguanLog);
            // 判断是不是json，是json才上传到OSS
            if (CommonUtil.isJson(ret1)) {
                // 传至oss
                InputStream in_withcode = new ByteArrayInputStream(ret1.getBytes("UTF-8"));
                try {
                    String url = AliOSSUtil.uploadFile(in_withcode, DIRPATH,miguanLog.getmId() + ".json");
                            /*uploadFileForNormol(in_withcode, DIRPATH, miguanLog.getId() + ".json",
                            Global.getString(MIGUANOSS));*/
                    miguanLog.setOssUrl(AliOSSUtil.getFilePath(url));
                    miguanLog.setFlag(SUCCESSFLAG);
                    miguanLog.setUploadTime(DateUtil.getNow());
                    rdMiguanLogDao.updateByPrimaryKey(miguanLog);
                } catch (Exception e) {
                    miguanLog.setFlag(SUCCESSFAIL);
                    rdMiguanLogDao.updateByPrimaryKey(miguanLog);
                    e.printStackTrace();
                }
            }
        }
        logger.info("=====================获取蜜罐接口信息结束=========================");
    }

    @Override
    public RdMiguanDTO findIsUpload(RdUserInfoDTO userInfo) {
        RdMiguan miguan = rdMiguanLogDao.findIsUpload(userInfo.getUserId());
        if(miguan != null) {
            RdMiguanDTO dto = new RdMiguanDTO();
            BeanUtils.copyProperties(miguan, dto);
            return dto;
        }
        return null;
    }
}
